package com.yj.springbootstudy.mulThread.demo;

import java.awt.*;

/**
 * 保护性暂停多线程模式
 * 原理：
 * 一个线程等待另外一个线程的结果
 */
public class Demo01 {


    public static void main(String[] args) {
        //两个线程共用一个结果对象
        GuardedObject guardedObject = new GuardedObject();
        Thread t1 = new Thread(() -> {
            try {
                System.out.println("等待结果返回。。。");
                Object o = guardedObject.get();
                System.out.printf("获取到的结果：%s", o);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                // 模拟其他业务操作
                Thread.sleep(3000);
                // 生产结果
                System.out.println("生产结果。。。");
                guardedObject.complete("do success");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
    }


}

class GuardedObject {

    private Object response;

    //获取结果
    public Object get() throws InterruptedException {
        synchronized (this) {
            while (response == null) {
                this.wait();
            }
        }
        return response;
    }

    //带超时时间的获取
    public Object get(long timeout) {

        synchronized (this) {
            long passed = 0;
            while (response == null) {
                long waitTime = passed - timeout;
                if (waitTime >= 0) {
                    break;
                }

                try {
                    this.wait(timeout);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                passed = System.currentTimeMillis() - timeout;

            }
        }
        return response;
    }


    //产生结果
    public void complete(Object response) {
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }

}
